Search for notes by fellow students, in your own course and all over the country.
Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.
Title: Reactjs Interview Questions Description: React is a JavaScript-based UI development library. Facebook and an open-source developer community run it. Although React is a library rather than a language, it is widely used in web development. The library first appeared in May 2013 and is now one of the most commonly used frontend libraries for web development.in this notes i have done 300+ interview questions and answers so that is best for interview from my side
Questions Core React What is React? What are the major features of React? What is JSX? What is the difference between Element and Component? How to create components in React? When to use a Class Component over a Function Component? What are Pure Components? What is state in React? What are props in React? What is the difference between state and props? Why should we not update the state directly? What is the purpose of callback function as an argument of setState()? What is the difference between HTML and React event handling? How to bind methods or event handlers in JSX callbacks? How to pass a parameter to an event handler or callback? What are synthetic events in React? What are inline conditional expressions? What is “key” prop and what is the benefit of using it in arrays of elements? What is the use of refs? How to create refs? What are forward refs? 1
No
...
Questions
60 61 62 63 64 65
How to use InnerHtml in React? How to use styles in React? How events are different in React? What will happen if you use setState in constructor? What is the impact of indexes as keys? Is it good to use setState() in componentWillMount() method? What will happen if you use props in initial state? How do you conditionally render components? Why we need to be careful when spreading props on DOM elements?? How you use decorators in React? How do you memoize a component? How you implement Server-Side Rendering or SSR? How to enable production mode in React? What is CRA and its benefits? What is the lifecycle methods order in mounting? What are the lifecycle methods going to be deprecated in React v16? What is the purpose of getDerivedStateFromProps() lifecycle method? What is the purpose of getSnapshotBeforeUpdate() lifecycle method? Do Hooks replace render props and higher order components? What is the recommended way for naming components? What is the recommended ordering of methods in component class? What is a switching component? Why we need to pass a function to setState()? What is strict mode in React? What are React Mixins? Why is isMounted() an anti-pattern and what is the proper solution? What are the Pointer Events supported in React? Why should component names start with capital letter? Are custom DOM attributes supported in React v16? What is the difference between constructor and getInitialState? Can you force a component to re-render without calling setState? What is the difference between super() and super(props) in React using ES6 classes? How to loop inside JSX?
Questions React Router What is React Router? How React Router is different from history library? What are the components of React Router v4? What is the purpose of push and replace methods of history? How do you programmatically navigate using React router v4? How to get query parameters in React Router v4 Why you get “Router may have only one child element” warning? How to pass params to history
...
Questions
162 163 164
How to use connect from React Redux? How to reset state in Redux? Whats the purpose of at symbol in the redux connect decorator? What is the difference between React context and React Redux? Why are Redux state functions called reducers? How to make AJAX request in Redux? Should I keep all component’s state in Redux store? What is the proper way to access Redux store? What is the difference between component and container in React Redux? What is the purpose of the constants in Redux? What are the different ways to write mapDispatchToProps()? What is the use of the ownProps parameter in mapStateToProps() and mapDispatchToProps()? How to structure Redux top level directories? What is redux-saga? What is the mental model of redux-saga? What are the differences between call and put in redux-saga What is Redux Thunk? What are the differences between redux-saga and redux-thunk What is Redux DevTools? What are the features of Redux DevTools? What are Redux selectors and Why to use them? What is Redux Form? What are the main features of Redux Form? How to add multiple middlewares to Redux? How to set initial state in Redux? How Relay is different from Redux? What is an action in Redux? React Native What is the difference between React Native and React? How to test React Native apps? How to do logging in React Native? How to debug your React Native? React supported libraries and Integration What is reselect and how it works? What is Flow? What is the difference between Flow and PropTypes?
No
...
js? What is the difference between React and Angular? Why React tab is not showing up in DevTools? What are styled components? Give an example of Styled Components? What is Relay? How to use TypeScript in create-react-app application? Miscellaneous What are the main features of reselect library? Give an example of reselect usage? Does the statics object work with ES6 classes in React? Can Redux only be used with React? Do you need to have a particular build tool to use Redux? How Redux Form initialValues get updated from state? How React PropTypes allow different type for one prop? Can I import an SVG file as react component? Why are inline ref callbacks or functions not recommended? What is render hijacking in React? What are HOC factory implementations? How to pass numbers to React component? Do I need to keep all my state into Redux? Should I ever use react internal state? What is the purpose of registerServiceWorker in React? What is React memo function? What is React lazy function? How to prevent unnecessary updates using setState? How do you render Array, Strings and Numbers in React 16 Version? How to use class field declarations syntax in React classes? What are hooks? What rules need to be followed for hooks? How to ensure hooks followed the rules in your project? What are the differences between Flux and Redux? What are the benefits of React Router V4? Can you describe about componentDidCatch lifecycle method signature?
What are the conditions to safely use the index as a key? Is it keys should be globally unique? What is the popular choice for form handling? What are the advantages of formik over redux form library? Why do you not required to use inheritance? Can I use web components in react application? What is dynamic import? What are loadable components? What is suspense component? What is route based code splitting? Give an example on How to use context? What is the purpose of default value in context? How do you use contextType? What is a consumer? How do you solve performance corner cases while using context? What is the purpose of forward ref in HOCs? Is it ref argument available for all functions or class components? Why do you need additional care for component libraries while using forward refs? How to create react class components without ES6? Is it possible to use react without JSX? What is diffing algorithm? What are the rules covered by diffing algorithm? When do you need to use refs? Is it prop must be named as render for render props? What are the problems of using render props with pure components? How do you create HOC using render props? What is windowing technique? How do you print falsy values in JSX? What is the typical use case of portals? How do you set default value for uncontrolled component? What is your favorite React stack? What is the difference between Real DOM and Virtual DOM? How to add Bootstrap to a react application? Can you list down top websites or applications using react as front end framework? Is it recommended to use CSS In JS technique in React?
No
...
9? What is the purpose of eslint plugin for hooks? What is the difference between Imperative and Declarative in React? What are the benefits of using typescript with reactjs? How do you make sure that user remains authenticated on page refresh while using Context API State Management? What are the benefits of new JSX transform? How does new JSX transform different from old transform? How do you get redux scaffolding using create-react-app? What are React Server components? What is prop drilling? What is state mutation and how to prevent it? What is the difference between useState and useRef hook?
Core React 1
...
It is used for handling view layer for web and mobile apps
...
React was first deployed on Facebook’s News Feed in 2011 and on Instagram in 2012
...
What are the major features of React? The major features of React are: • It uses VirtualDOM instead of RealDOM considering that RealDOM manipulations are expensive
...
• Follows Unidirectional data flow or data binding
...
� Back to Top 3
...
Basically it just provides syntactic sugar for the React
...
In the example below text inside
tag is returned as JavaScript function to the render function
...
Component { render() { return(
{'Welcome to React world!'}
) } } � Back to Top 4
...
Elements can 11
contain other Elements in their props
...
Once an element is created, it is never mutated
...
createElement( 'div', {id: 'login-btn'}, 'Login' ) The above React
...
render():
Login
Whereas a component can be declared in several different ways
...
In either case, it takes props as an input, and returns a JSX tree as the output: const Button = ({ onLogin }) =>
Login
Then JSX gets transpiled to a React
...
createElement( 'div', { id: 'login-btn', onClick: onLogin }, 'Login' ) � Back to Top 5
...
1
...
Those are pure JavaScript functions that accept props object as the first parameter and return React elements:
12
“jsx harmony function Greeting({ message }) {
{Hello, ${message}‘}
return
} “‘ 2
...
The above function component can be written as: jsx harmony render() { } }
class Greeting extends React
...
props
...
When to use a Class Component over a Function Component? If the component needs state or lifecycle methods then use class component otherwise use function component
...
8 with the addition of Hooks, you could use state , lifecycle methods and other features that were only available in class component right in your function component
...
What are Pure Components? React
...
Component except that it handles the shouldComponentUpdate() method for you
...
Component on the other hand won’t compare current props and state to next out of the box
...
� Back to Top 8
...
We should always try to make our state as simple as possible and minimize the number of stateful components
...
Component { constructor(props) { super(props) this
...
state
...
e
...
� Back to Top 9
...
They are single values or objects containing a set of values that are passed to components on creation using a naming convention similar to HTML-tag attributes
...
14
The primary purpose of props in React is to provide following component functionality: 1
...
2
...
3
...
props
...
For example, let us create an element with reactProp property: jsx harmony
This reactProp (or whatever you came up with) name then becomes a property attached to React’s native props object which originally already exists on all components created using React library
...
reactProp � Back to Top 10
...
While both of them hold information that influences the output of render, they are different in their functionality with respect to component
...
� Back to Top 11
...
//Wrong this
...
message = 'Hello world' Instead use setState() method
...
When state changes, the component responds by rerendering
...
setState({ message: 'Hello World' }) Note: You can directly assign to the state object either in constructor or using latest javascript’s class field declaration syntax
...
What is the purpose of callback function as an argument of setState()? The callback function is invoked when setState finished and the component gets rendered
...
Note: It is recommended to use lifecycle method rather than this callback function
...
log('The name has updated and component re-ren � Back to Top 13
...
In HTML, the event name usually represents in lowercase as a convention:
{'Click
3
...
jsx harmony handleClick() { console
...
handleClick()}>Click Me; } Note: If the callback is passed as prop to child components, those components might do an extra re-rendering
...
bind() or public class fields syntax approach considering performance
...
How to pass a parameter to an event handler or callback? You can use an arrow function to wrap around an event handler and pass parameters:
17
jsx harmony this
...
bind: jsx harmony
...
bind(this, id)} /> Apart from these two approaches, you can also pass arguments to a function which is defined as arrow function jsx harmony onClick={this
...
log("Hello, your ticket number is", id) }; � Back to Top 16
...
Its API is same as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers
...
What are inline conditional expressions? You can use either if statements or ternary expressions which are available from JS to conditionally render expressions
...
jsx harmony
Hello!
{ !isLogin?
unread messages
...
messages
...
length} :
You
}
� Back to Top 18
...
Key prop helps React identify which items have changed, are added, or are removed
...
map((todo) => key={todo
...
text} ) 18
When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort: jsx harmony const todoItems = todos
...
text} ) Note: 1
...
This can negatively impact performance and may cause issues with component state
...
If you extract list item as separate component then apply keys on list component instead of li tag
...
There will be a warning message in the console if the key prop is not present on list items
...
What is the use of refs? The ref is used to return a reference to the element
...
� Back to Top 20
...
This is a recently added approach
...
createRef() method and attached to React elements via the ref attribute
...
For example, the search bar component’s input element is accessed as follows, jsx harmony class SearchBar extends Component { constructor(props) { super(props); this
...
state = { term: '' }; this
...
txtSearch = e; } } onInputChange(event) {
19
this
...
txtSearch
...
onInputChange
...
state ref={this
...
Note: You can also use inline ref callbacks even though it is not a recommended approach
...
What are forward refs? Ref forwarding is a feature that lets some components take a ref they receive, and pass it further down to a child
...
forwardRef((props, ref) => ( {props
...
createRef(); {‘Forward Ref’} “‘ � Back to Top 22
...
Because findDOMNode() prevents certain improvements in React in the future
...
scrollIntoView() } render() { return } } The recommended approach is: class MyComponent extends Component { constructor(props){ super(props); this
...
node
...
scrollIntoView(); } render() { return
...
Why are String Refs legacy? If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like ref={'textInput'}, and the DOM node is accessed as this
...
textInput
...
String refs were removed in React v16
...
They force React to keep track of currently executing component
...
2
...
Callback refs are perfectly composable
...
They don’t work with static analysis like Flow
...
refs, as well as its type (which could be different)
...
4
...
g
...
Ref will get attached to DataTable rather than MyComponent: return ; // This would work though! Callback refs are awesome
...
21
What is Virtual DOM? The Virtual DOM (VDOM) is an in-memory representation of Real DOM
...
It’s a step that happens between the render function being called and the displaying of elements on the screen
...
� Back to Top 25
...
1
...
Figure 2: vdom 2
...
3
...
� Back to Top 26
...
The Virtual DOM is a concept implemented by libraries in JavaScript on top of browser APIs
...
22
Figure 3: vdom2
Figure 4: vdom3
23
What is React Fiber? Fiber is the new reconciliation engine or reimplementation of core algorithm in React v16
...
� Back to Top 28
...
Its headline feature is incremental rendering: the ability to split rendering work into chunks and spread it out over multiple frames
...
Ability to split interruptible work in chunks
...
Ability to prioritize, rebase and reuse work in progress
...
Ability to yield back and forth between parents and children to support layout in React
...
Ability to return multiple elements from render()
...
Better support for error boundaries
...
What are controlled components? A component that controls the input elements within the forms on subsequent user input is called Controlled Component, i
...
For example, to write all the names in uppercase letters, we use handleChange as below, handleChange(event) { this
...
target
...
toUpperCase()}) } � Back to Top 30
...
This is a bit more like traditional HTML
...
“‘jsx harmony class UserProfile extends React
...
handleSubmit = this
...
bind(this) this
...
createRef() } handleSubmit(event) { alert(‘A name was submitted:’ + this
...
current
...
preventDefault() } render() { return ( {‘Name:’} ); } } “‘ In most cases, it’s recommend to use controlled components to implement forms
...
The alternative is uncontrolled components, where form data is handled by the DOM itself
...
What is the difference between createElement and cloneElement? JSX elements will be transpiled to React
...
Whereas cloneElement is used to clone an element and pass it new props
...
What is Lifting State Up in React? When several components need to share the same changing data then it is recommended to lift the shared state up to their closest common ancestor
...
� Back to Top
25
33
...
Mounting: The component is ready to mount in the browser DOM
...
2
...
This phase covers getDerivedStateFromProps(), shouldComponentUpdate(), render(), getSnapshotBeforeUpdate() and componentDidUpdate() lifecycle methods
...
Unmounting: In this last phase, the component is not needed and gets unmounted from the browser DOM
...
It’s worth mentioning that React internally has a concept of phases when applying changes to the DOM
...
Render The component will render without any side effects
...
2
...
3
...
React 16
...
3 � Back to Top 34
...
3 • componentWillMount: Executed before rendering and is used for App level configuration in your root component
...
4+
Figure 6: phases 16
...
• componentWillReceiveProps: Executed when particular prop updates to trigger state transitions
...
By default it returns true
...
It is a great place to improve performance as it allows you to prevent a re-render if component receives new prop
...
• componentDidUpdate: Mostly it is used to update the DOM in response to prop or state changes
...
React 16
...
This exists for rare use cases where you need a derived state
...
• componentDidMount: Executed after first rendering and where all AJAX requests, DOM or state updates, and set up event listeners should occur
...
By default, it returns true
...
It is a great place to improve performance as it allows you to prevent a re-render if component receives a new prop
...
Any value returned by this will be passed into componentDidUpdate()
...
e
...
• componentDidUpdate: Mostly it is used to update the DOM in response to prop or state changes
...
• componentWillUnmount It will be used to cancel any outgoing network requests, or remove all event listeners associated with the component
...
28
What are Higher-Order Components? A higher-order component (HOC) is a function that takes a component and returns a new component
...
We call them pure components because they can accept any dynamically provided child component but they won’t modify or copy any behavior from their input components
...
2
...
4
...
Render hijacking
...
Props manipulation
...
How to create props proxy for HOC component? You can add/edit props passed to the component using props proxy pattern like this: “‘jsx harmony function HOC(WrappedComponent) { return class Test extends Component { render() { const newProps = { title: ‘New Header’, footer: false, showFeatureX: false, showFeatureY: true } return
...
props} {
...
What is context? Context provides a way to pass data through the component tree without having to pass props down manually at every level
...
const {Provider, Consumer} = React
...
29
What is children prop? Children is a prop (this
...
children) that allows you to pass components as data to other components, just like any other prop you use
...
There are several methods available in the React API to work with this prop
...
Children
...
Children
...
Children
...
Children
...
Children
...
A simple usage of children prop looks as below, “‘jsx harmony const MyDiv = React
...
props
...
render( {‘Hello’} {‘World’} , node ) “‘ � Back to Top 39
...
Single-line comments: jsx harmony
{/* Single-line comments(In vanilla JavaScript, the single-line comments are represented by double slash(//)) */} {`Welcome ${user}, let's play React`}
Multi-line comments: jsx harmony
{/* Multi-line comments for more than one line */} {`Welcome ${user}, let's play React`}
� Back to Top 40
...
The same applies to ES6 sub-classes as well
...
props in your child constructors
...
Component { constructor(props) { super(props) console
...
props) // prints { name: 'John', age: 42 } } } Not passing props: class MyComponent extends React
...
log(this
...
log(props) // prints { name: 'John', age: 42 } } render() { // no difference outside constructor console
...
props) // prints { name: 'John', age: 42 } } } The above code snippets reveals that this
...
It would be the same outside the constructor
...
What is reconciliation? When a component’s props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one
...
This process is called reconciliation
...
How to set state with a dynamic key name? If you are using ES6 or the Babel transpiler to transform your JSX code then you can accomplish this with computed property names
...
setState({ [event
...
id]: event
...
value }) } � Back to Top 43
...
jsx harmony render() { // Wrong: handleClick is called instead of passed as a reference! return
...
handleClick}>{'Click Me'} } � Back to Top 44
...
lazy function supports default exports only
...
It also ensures that tree shaking keeps working and don’t pull unused components
...
js export const SomeComponent = /*
...
*/; and reexport MoreComponents
...
js javascript // IntermediateComponent
...
/MoreComponents
...
/IntermediateComponent
...
32
Why React uses className over class attribute? class is a keyword in JavaScript, and JSX is an extension of JavaScript
...
Pass a string as the className prop
...
What are fragments? It’s a common pattern in React which is used for a component to return multiple elements
...
jsx harmony render() { return (
...
Fragment> ) } There is also a shorter syntax, but it’s not supported in many tools: jsx harmony render() { return ( >
<> ) }
� Back to Top 47
...
Fragments are a bit faster and use less memory by not creating an extra DOM node
...
2
...
3
...
� Back to Top 48
...
33
ReactDOM
...
The second argument is a DOM element
...
What are stateless components? If the behaviour is independent of its state then it can be a stateless component
...
But unless you need to use a lifecycle hook in your components, you should go for function components
...
� Back to Top 50
...
These stateful components are always class components and have a state that gets initialized in the constructor
...
state = { count: 0 } } render() { //
...
8 Update: Hooks let you use state and other React features without writing classes
...
How to apply validation on props in React? When the application is running in development mode, React will automatically check all props that we set on components to make sure they have correct type
...
It’s disabled in production mode due to performance impact
...
We can define propTypes for User component as below: “‘jsx harmony import React from ‘react’ import PropTypes from ‘proptypes’ class User extends React
...
string
...
number
...
props
...
props
...
5 *PropTypes* were moved from `React
...
propTypes = { name: PropTypes
...
isRequired, age: PropTypes
...
isRequired } � Back to Top 52
...
2
...
4
...
JSX makes code easy to read and write
...
Easy to integrate with frameworks (Angular, Backbone) since it is only a view library
...
Easy to write unit and integration tests with tools such as Jest
...
What are the limitations of React? Apart from the advantages, there are few limitations of React too, 1
...
2
...
3
...
4
...
36
5
...
� Back to Top 54
...
A class component becomes an error boundary if it defines a new lifecycle method called componentDidCatch(error, info) or static getDerivedStateFromError(): “‘jsx harmony class ErrorBoundary extends React
...
state = { hasError: false } } componentDidCatch(error, info) { // You can also log the error to an error reporting service logErrorToMyService(error, info) } static getDerivedStateFromError(error) { // Update state so the next render will show the fallback UI
...
state
...
’} } return this
...
children }} After that use it as a regular component: ```jsx harmony
� Back to Top 55
...
It has been renamed to componentDidCatch in React v16
...
What are the recommended ways for static type checking? Normally we use PropTypes library (React
...
5) for type checking in the React applications
...
� Back to Top 57
...
Most of the components are not required to use this module
...
� Back to Top 58
...
If the React element was previously rendered into container, it will perform an update on it and only mutate the DOM as necessary to reflect the latest changes
...
render(element, container, [callback]) If the optional callback is provided, it will be executed after the component is rendered or updated
...
What is ReactDOMServer? The ReactDOMServer object enables you to render components to static markup (typically used on node server)
...
The following methods can be used in both the server and browser environments: 1
...
renderToStaticMarkup() For example, you generally run a Node-based web server like Express, Hapi, or Koa, and you call renderToString to render your root component to a string, which you then send as response
...
/MyPage' app
...
write('My Page') res
...
write(renderToString()) res
...
end() }) � Back to Top 60
...
Just like innerHTML, it is risky to use this attribute considering cross-site scripting (XSS) attacks
...
In this example MyComponent uses dangerouslySetInnerHTML attribute for setting HTML markup: “‘jsx harmony function createMarkup() { return { __html: ‘First · Second’ } } function MyComponent() { return } “‘ � Back to Top 61
...
This is consistent with the DOM style JavaScript property, is more efficient, and prevents XSS security holes
...
g
...
style
...
� Back to Top 62
...
React event handlers are named using camelCase, rather than lowercase
...
With JSX you pass a function as the event handler, rather than a string
...
What will happen if you use setState() in constructor? When you use setState(), then apart from assigning to the object state React also re-renders the component and all its children
...
So we need to use this
...
� Back to Top 64
...
In the below code snippet each element’s key will be based on ordering, rather than tied to the data that is being represented
...
jsx harmony {todos
...
todo}
If you use element data for unique key, assuming todo
...
jsx harmony {todos
...
todo}
key={todo
...
Is it good to use setState() in componentWillMount() method? Yes, it is safe to use setState() inside componentWillMount() method
...
componentWillMount() is invoked immediately before mounting occurs
...
Avoid introducing any side-effects or subscriptions in this method
...
jsx harmony componentDidMount() { axios
...
then((result) => { this
...
result
...
What will happen if you use props in initial state? If the props on the component are changed without the component being refreshed, the new prop value will never be displayed because the constructor function will never update the current state of the component
...
The below component won’t display the updated input value: “‘jsx harmony class MyComponent extends React
...
state = { records: [], inputValue: this
...
inputValue }; } render() { return
41
{this
...
inputValue} }} Using props inside render method will update the value: ```jsx harmony class MyComponent extends React
...
state = { record: [] } } render() { return
{this
...
inputValue}
} } � Back to Top 67
...
JSX does not render false or undefined, so you can use conditional short-circuiting to render a given part of your component only if a certain condition is true
...
) � Back to Top 68
...
Instead we can use prop destructuring 42
with
...
For example, “‘jsx harmony const ComponentA = () => const ComponentB = ({ isDisplay, …domProps }) =>
{‘ComponentB’} “‘ � Back to Top 69
...
Decorators are flexible and readable way of modifying component functionality
...
Component { //…
...
Component { componentDidMount() { document
...
this
...
� Back to Top 70
...
For example moize library can memoize the component in another component
...
/components/Component’ // this module exports a non-memoized component
How you implement Server Side Rendering or SSR? React is already equipped to handle rendering on Node servers
...
“‘jsx harmony import ReactDOMServer from ‘react-dom/server’ import App from ‘
...
renderToString() “‘ This method will output the regular HTML as a string, which can be then placed inside a page body as part of the server response
...
� Back to Top 72
...
Apart from this, if you minify the code, for example, Uglify’s dead-code elimination to strip out development only code and comments, it will drastically reduce the size of your bundle
...
44
What is CRA and its benefits? The create-react-app CLI tool allows you to quickly create & run React applications with no configuration step
...
2
...
4
...
Language extras beyond ES6 like the object spread operator
...
A fast interactive unit test runner with built-in support for coverage reporting
...
A live development server that warns about common mistakes
...
A build script to bundle JS, CSS, and images for production, with hashes and sourcemaps
...
What is the lifecycle methods order in mounting? The lifecycle methods are called in the following order when an instance of a component is being created and inserted into the DOM
...
2
...
4
...
45
What are the lifecycle methods going to be deprecated in React v16? The following lifecycle methods going to be unsafe coding practices and will be more problematic with async rendering
...
componentWillMount() 2
...
componentWillUpdate() Starting with React v16
...
� Back to Top 76
...
It can return an object to update state, or null to indicate that the new props do not require any state updates
...
Component { static getDerivedStateFromProps(props, state) { //
...
� Back to Top 77
...
The return value from this method will be passed as the third parameter to componentDidUpdate()
...
Component { getSnapshotBeforeUpdate(prevProps, prevState) { //
...
� Back to Top 78
...
� Back to Top 79
...
Using displayName for naming component: export default React
...
}) The recommended approach: export default class TodoApp extends React
...
} also const TodoApp = () => { //
...
What is the recommended ordering of methods in component class? Recommended ordering of methods from mounting to render stage: 1
...
constructor() 47
3
...
5
...
7
...
9
...
11
...
getter methods for render like getSelectReason() or getFooterContent() 13
...
render() � Back to Top 81
...
We need to use object to map prop values to components
...
/HomePage’ import AboutPage from ‘
...
/ServicesPage’ import ContactPage from ‘
...
page] || ContactPage return } // The keys of the PAGES object can be used in the prop types to catch dev-time errors
...
propTypes = { page: PropTypes
...
keys(PAGES))
...
Why we need to pass a function to setState()? The reason behind for this is that setState() is an asynchronous operation
...
That means you
48
should not rely on the current state when calling setState() since you can’t be sure what that state will be
...
By doing this you can avoid issues with the user getting the old state value on access due to the asynchronous nature of setState()
...
After three consecutive increment operations, the value is going to be incremented only by one
...
state
...
setState({ count: this
...
count + 1 }) this
...
state
...
setState({ count: this
...
count + 1 }) // this
...
count === 1, not 3 If we pass a function to setState(), the count gets incremented correctly
...
setState((prevState, props) => ({ count: prevState
...
increment })) // this
...
count === 3 as expected (OR) Why function is preferred over object for setState()? React may batch multiple setState() calls into a single update for performance
...
props and this
...
This counter example will fail to update as expected: // Wrong this
...
state
...
props
...
That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument
...
setState((prevState, props) => ({ counter: prevState
...
increment })) � Back to Top 83
...
StrictMode is a useful component for highlighting potential problems in an application
...
It activates additional checks and warnings for its descendants
...
“‘jsx harmony import React from ‘react’ function ExampleApplication() { return (
...
StrictMode>
) } “‘ In the example above, the strict mode checks apply to and components only
...
What are React Mixins? Mixins are a way to totally separate components to have a common functionality
...
context; /*
...
context; /* render something based on the value of MyContext */ } } MyClass
...
Static field You can use a static class field to initialize your contextType using public class field syntax
...
Component { static contextType = MyContext; render() { let value = this
...
What is a consumer? A Consumer is a React component that subscribes to context changes
...
The value argument passed to the function will be equal to the value prop of the closest Provider for this context above in the tree
...
Consumer> {value => /* render something based on the context value */ }
...
How do you solve performance corner cases while using context? The context uses reference identity to determine when to re-render, there are some gotchas that could trigger unintentional renders in consumers when a provider’s parent re-renders
...
class App extends React
...
Component { constructor(props) { super(props); this
...
state
...
What is the purpose of forward ref in HOCs? Refs will not get passed through because ref is not a prop
...
If you add a ref to a HOC, the ref will refer to the outermost container component, not the wrapped component
...
For example, we can explicitly forward refs to the inner FancyButton component using the React
...
The below HOC logs all props, function logProps(Component) { class LogProps extends React
...
log('old props:', prevProps); console
...
props); } render() { const {forwardedRef,
...
props; // Assign the custom prop "forwardedRef" as a ref return
...
forwardRef((props, ref) => { 135
return
...
Component { focus() { //
...
} export default logProps(FancyButton); Now let’s create a ref and pass it to FancyButton component
...
import FancyButton from '
...
createRef(); ref
...
focus(); label="Click Me" handleClick={handleClick} ref={ref} />; � Back to Top 283
...
The second ref argument only exists when you define a component with React
...
� Back to Top 284
...
This is because your library likely has a different behavior such as what
136
refs get assigned to, and what types are exported
...
� Back to Top 285
...
For default props, you need to define getDefaultProps() as a function on the passed object
...
var Greeting = createReactClass({ getDefaultProps: function() { return { name: 'Jhohn' }; }, getInitialState: function() { return {message: this
...
message}; }, handleClick: function() { console
...
state
...
props
...
i
...
bind(this) with in constructor for event handlers
...
Is it possible to use react without JSX? Yes, JSX is not mandatory for using React
...
Each JSX element is just syntactic sugar for calling React
...
children)
...
Component { render() {
137
return
Hello {this
...
message}
; } } ReactDOM
...
getElementById('root') ); You can write the same code without JSX as below, class Greeting extends React
...
createElement('div', null, `Hello ${this
...
message}`); } } ReactDOM
...
createElement(Greeting, {message: 'World'}, null), document
...
What is diffing algorithm? React needs to use algorithms to find out how to efficiently update the UI to match the most recent tree
...
However, the algorithms have a complexity in the order of O(n3) where n is the number of elements in the tree
...
This is far too expensive
...
Two elements of different types will produce different trees
...
The developer can hint at which child elements may be stable across different renders with a key prop
...
What are the rules covered by diffing algorithm? When diffing two trees, React first compares the two root elements
...
It covers
138
the below rules during reconciliation algorithm, 1
...
For example, elements to , or from to of different types lead a full rebuild
...
DOM Elements Of The Same Type: When comparing two React DOM elements of the same type, React looks at the attributes of both, keeps the same underlying DOM node, and only updates the changed attributes
...
Component Elements Of The Same Type: When a component updates, the instance stays the same, so that state is maintained across renders
...
After that, the render() method is called and the diff algorithm recurses on the previous result and the new result
...
Recursing On Children: when recursing on the children of a DOM node, React just iterates over both lists of children at the same time and generates a mutation whenever there’s a difference
...
first
second
first
second
third
5
...
When children have keys, React uses the key to match children in the original tree with children in the subsequent tree
...
When do you need to use refs? There are few use cases to go for refs, 1
...
2
...
3
...
� Back to Top 290
...
i
...
Lets take an example with the children prop for render props, (
The mouse position is {mouse
...
y}
)}/> Actually children prop doesn’t need to be named in the list of “attributes” in JSX element
...
x}, {mouse
...
Mouse
...
func
...
What are the problems of using render props with pure components? If you create a function inside a render method, it negates the purpose of pure component
...
You can solve this issue by defining the render function as instance method
...
How do you create HOC using render props? You can implement most higher-order components (HOC) using a regular component with a render prop
...
function withMouse(Component) { return class extends React
...
this
...
� Back to Top 293
...
If your application renders long lists of data then this technique is recommended
...
� Back to Top 294
...
If you still want to display them then you need to convert it to string
...
� Back to Top 295
...
g
...
For example, dialogs, global message notifications, hovercards, and tooltips
...
How do you set default value for uncontrolled component? In React, the value attribute on form elements will override the value in the DOM
...
To handle this case, you can specify a defaultValue attribute instead of value
...
handleSubmit}>